package com.example.itcacp.service.impl;

import com.example.itcacp.dto.response.ApiResponse;
import com.example.itcacp.dto.response.FileNode;
import com.example.itcacp.entity.Project;
import com.example.itcacp.repository.mybatis.ProjectMapper;
import com.example.itcacp.service.FileService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private ProjectMapper projectMapper;

    @Override
    public ApiResponse<?> createFolder(Long projectId, String folderName) {
        Project project = projectMapper.selectProjectById(projectId);  // 查找项目
        String repoPath = project.getPath ();  // 拿到仓库地址
        Path folderPath = Paths.get(repoPath, folderName);  // 构建路径

        try {
            if (Files.notExists(folderPath)) {
                Files.createDirectories(folderPath);
                return ApiResponse.success(null);
            } else {
                return ApiResponse.error("400", "文件夹已存在");
            }
        } catch (IOException e) {
            return ApiResponse.error("500", "创建文件夹失败: " + e.getMessage());
        }
    }

    @Override
    public ApiResponse<FileNode> getFileTree(Long projectId) throws IOException {
        Project project = projectMapper.selectProjectById(projectId);  // 查找项目
        String repoPath = project.getPath ();  // 拿到仓库地址
        Path projectPath = Paths.get(repoPath);

        if (Files.notExists(projectPath)) {
            return ApiResponse.error("404", "项目目录不存在");
        }

        FileNode rootNode = buildFileTree(projectPath, projectPath);
        return ApiResponse.success(rootNode);
    }

    private FileNode buildFileTree(Path rootPath, Path currentPath) throws IOException {
        FileNode node = new FileNode();
        node.setId(currentPath.toString());
        node.setLabel(currentPath.getFileName().toString());
        node.setDirectory (Files.isDirectory(currentPath));

        if (node.isDirectory()) {
            List<FileNode> children = new ArrayList<> ();
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(currentPath)) {
                for (Path path : stream) {
                    children.add(buildFileTree(rootPath, path));
                }
            }
            node.setChildren(children);
        }

        return node;
    }


}
